//
//  WUCopyLabel.m
//  BESTKEEP
//
//  Created by 武探 on 2016/10/11.
//  Copyright © 2016年 YISHANG. All rights reserved.
//

#import "WUCopyLabel.h"

@implementation WUCopyLabel {
    BOOL _copyMenuShowing;
}

-(instancetype)initWithFrame:(CGRect)frame {
    self = [super initWithFrame: frame];
    if(self) {
        [self addAction];
    }
    return self;
}

-(BOOL)canBecomeFirstResponder {
    return YES;
}

-(void)copy:(id)sender {
    UIPasteboard *pboard = [UIPasteboard generalPasteboard];
    pboard.string = self.text;
}

-(BOOL)canPerformAction:(SEL)action withSender:(id)sender {
    if(action == @selector(copy:)) {
        return YES;
    }
    return NO;
}

-(void)addAction {
    self.userInteractionEnabled = YES;
    
    UILongPressGestureRecognizer *longPressRecognizer = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(longPressGecognizer:)];
    [self addGestureRecognizer:longPressRecognizer];
}

-(void)longPressGecognizer:(UIGestureRecognizer*)sender {
    
    if(_copyMenuShowing || !self.text || self.text.length == 0) {
        return;
    }
    
    [self becomeFirstResponder];
    
//    UIMenuItem *copyItem = [[UIMenuItem alloc] initWithTitle:@"复制" action:@selector(copy:)];
//    UIMenuItem *copyItem = [[UIMenuItem alloc] init];
//    [[UIMenuController sharedMenuController] setMenuItems:@[copyItem]];
    [[UIMenuController sharedMenuController] setTargetRect:self.frame inView:self.superview];
    [[UIMenuController sharedMenuController] setMenuVisible:YES animated: YES];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(menuControllerDidHideMenu:) name:UIMenuControllerDidHideMenuNotification object:nil];
    
    _copyMenuShowing = YES;
    
    UIColor *color = [UIColor colorWithRed:0.910 green:0.910 blue:0.910 alpha:1.00];
    self.backgroundColor = color;
}

-(void)menuControllerDidHideMenu:(NSNotification*)notification {
    self.backgroundColor = [UIColor clearColor];
    _copyMenuShowing = NO;
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

-(void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

@end
